﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;

public partial class SYS_POPEDOM_Dept_Create : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ShowControl();
            if (!String.IsNullOrEmpty(Request.QueryString["DeptID"]))
            {
                ViewState["DeptID"] = Request.QueryString["DeptID"].Trim();
                ShowDeptInfo(ViewState["DeptID"].ToString());
            }
            else
            {
                if (!String.IsNullOrEmpty(Request.QueryString["PARENT_ID"]))
                {
                    ViewState["ParentID"] = Request.QueryString["PARENT_ID"].Trim();
                    txtDeptParent.Text = Request.QueryString["PARENT_NAME"];
                    txtInnerDept_No.Text = "000";
                }
                else
                {
                    ViewState["ParentID"] = "";
                }
            }
        }
    }

    protected void GetPY(object sender, DirectEventArgs e)
    {
        string Name = txtDeptName.Text.Trim();
        if (!string.IsNullOrEmpty(Name))
        {
            txtDeptPym.Text = GetPinyinByName(Name);
        }
        DataTable dt_SYS_DEPT = CommonLib.BLL.SYS_DEPT.GetList("DEPT_PYM IS NULL").Tables[0];
        foreach (DataRow item in dt_SYS_DEPT.Rows)
        {
            CommonLib.Model.SYS_DEPT model = CommonLib.BLL.SYS_DEPT.GetModel(Convert.ToString(item["DEPT_ID"]));
            model.DEPT_PYM = GetPinyinByName(model.DEPT_NAME);
            CommonLib.BLL.SYS_DEPT.Update(model);
        }
    }

    private void ShowControl()
    {
        if (Request.QueryString["type"] == "1")
        {
            txtDeptNo.FieldLabel = "机构编号";
            txtDeptName.FieldLabel = "机构名称";
            cmbDeptType.Visible = false;
            txtDeptParent.FieldLabel = "上级机构";
            RadioGroup1.Visible = false;
        }
        LoadDropDown(cmbDeptType, "", "部门类型");
    }

    private void BindStore1(string deptId)
    {
        DataTable GridData = CommonLib.BLL.SYS_USER.GetList(" is_manager=1 and del_flag=0 and dept_id = '" + deptId + "' ", "display_order").Tables[0];
        this.Store1.DataSource = GridData;
        this.Store1.DataBind();
    }
    //保存部门信息  
    [DirectMethod]
    public string SaveDept()
    {
        if (txtDeptNo.Text.Trim() == "")
        {
            X.Msg.Alert("系统提示", "部门编号不能为空！").Show();
            return "false";
        }
        if (txtDeptName.Text.Trim() == "")
        {
            X.Msg.Alert("系统提示", "部门名称不能为空！").Show();
            return "false";
        }
        if (txtInnerDept_No.Text.Trim() == "")
        {
            X.Msg.Alert("系统提示", "部门条码不能为空！").Show();
            return "false";
        }
        if (txtInnerDept_No.Text.Trim().Length != 3)
        {
            X.Msg.Alert("系统提示", "条码代码应为3位！").Show();
            return "false";
        }
        int n = 0;
        if (!int.TryParse(txtInnerDept_No.Text.Trim(), out n))
        {
            X.Msg.Alert("系统提示", "条码代码应为3位数字！").Show();
            return "false";
        }
        CommonLib.Model.SYS_DEPT modelDept = new CommonLib.Model.SYS_DEPT();
        if (null != ViewState["DeptID"])
        {
            modelDept = CommonLib.BLL.SYS_DEPT.GetModel(ViewState["DeptID"].ToString());
        }
        modelDept.DEPT_NO = txtDeptNo.Text.Trim();
        modelDept.DEPT_NAME = txtDeptName.Text.Trim();
        modelDept.DEPT_TYPE = cmbDeptType.SelectedItem.Value.ToString();
        modelDept.DEL_FLAG = 0;
        modelDept.PARENT_ID = ViewState["ParentID"].ToString();
        modelDept.MANAGER_ID = "";// extcomb_Manager.SelectedItem.Value;
        modelDept.MANAGER_NAME = "";// extcomb_Manager.SelectedItem.Text;
        modelDept.DEPT_PYM = txtDeptPym.Text.Trim();
        modelDept.AREA = exttxtf_AREA.Text.Trim();
        modelDept.INNERDEPT_NO = txtInnerDept_No.Text.Trim();//部门条码
        if (rdoDeptVirtual1.Checked)
            modelDept.IS_VIRTUAL = 1;
        else
            modelDept.IS_VIRTUAL = 0;

        try
        {
            if (null != ViewState["DeptID"])
            {
                int c = CommonLib.BLL.SYS_DEPT.GetRecorderCount(string.Format("INNERDEPT_NO='{0}' and DEPT_ID<>{1} and INNERDEPT_NO<>'000' ", txtInnerDept_No.Text.Trim(), ViewState["DeptID"]));
                if (c > 0)
                {
                    X.Msg.Alert("系统提示", "保存失败！</br>部门条码不能重复", "txtInnerDept_No.focus();").Show();
                    return "false";
                }
                modelDept.DEPT_ID = ViewState["DeptID"].ToString().Trim();
                CommonLib.BLL.SYS_DEPT.Update(modelDept);
            }
            else
            {
                int c = CommonLib.BLL.SYS_DEPT.GetRecorderCount(string.Format("INNERDEPT_NO='{0}' and INNERDEPT_NO<>'000' ", txtInnerDept_No.Text.Trim()));
                if (c > 0)
                {
                    X.Msg.Alert("系统提示", "保存失败！</br>部门条码不能重复", "txtInnerDept_No.focus();").Show();
                    return "false";
                }
                modelDept.DEPT_ID = CommonLib.BLL.SYS_DEPT.GetNewDeptId(ViewState["ParentID"].ToString());
                if (modelDept.DEPT_ID == "")
                    modelDept.DEPT_ID = ViewState["ParentID"].ToString() + "01";
                modelDept.IS_SUPPLY = short.Parse(Request.QueryString["type"].ToString());
                if (modelDept.IS_SUPPLY == 0)
                {
                    CommonLib.Model.SYS_DEPT p_model = CommonLib.BLL.SYS_DEPT.GetModel(ViewState["ParentID"].ToString());
                    if (p_model.IS_SUPPLY == 0)
                        modelDept.FOR_SUPPLY = p_model.FOR_SUPPLY;
                    else
                        modelDept.FOR_SUPPLY = p_model.DEPT_ID;
                }
                else
                    modelDept.FOR_SUPPLY = modelDept.DEPT_ID;

                modelDept.DEPT_INDEX = CommonLib.BLL.SYS_DEPT.GetNewID();
                CommonLib.BLL.SYS_DEPT.Add(modelDept);

            }
        }
        catch (Exception ex)
        {
            X.Msg.Alert("系统提示", ex.Message).Show();
            return "false";
        }

        return "true";
    }

    //根据deptid显示数据
    private void ShowDeptInfo(string deptId)
    {
        CommonLib.Model.SYS_DEPT oModel = CommonLib.BLL.SYS_DEPT.GetModel(deptId);
        BindStore1(oModel.DEPT_ID);
        txtDeptNo.Text = oModel.DEPT_NO;
        txtDeptName.Text = oModel.DEPT_NAME;
        txtDeptPym.Text = oModel.DEPT_PYM;
        txtDeptParent.Text = CommonLib.BLL.SYS_DEPT.GetList(" del_flag =0 and DEPT_ID ='" + oModel.PARENT_ID + "' ").Tables[0].Rows[0]["DEPT_NAME"].ToString(); ;
        cmbDeptType.Value = oModel.DEPT_TYPE;
        txtInnerDept_No.Text = oModel.INNERDEPT_NO;
        exttxtf_AREA.Text = oModel.AREA;
        int deptKind = oModel.DEPT_KIND;
        extcomb_Manager.SelectedItem.Value = oModel.MANAGER_ID;

        if (oModel.IS_VIRTUAL == 0)
        {
            rdoDeptVirtual1.Checked = false;
            rdoDeptVirtual2.Checked = true;
        }
        else
        {
            rdoDeptVirtual1.Checked = true;
            rdoDeptVirtual2.Checked = false;
        }

        ViewState["ParentID"] = oModel.PARENT_ID.Trim();
    }

    /// <summary>
    /// 获取一个新的InnerDept_No
    /// </summary>
    [DirectMethod]
    public void GetNewInnerDept_No()
    {
        string sql = @" SELECT INNERDEPT_NO+','  FROM SYS_DEPT where (ltrim(rtrim(INNERDEPT_NO)) <> '' and INNERDEPT_NO is not null and INNERDEPT_NO<>'000' ) 
        order by CAST( INNERDEPT_NO as int)
        FOR XML PATH('') ";
        int val = 1;

        DataTable dt = CommonLib.BLL.BS_DATASET_SQL.SqlGetTable(sql);
        if (dt.Rows.Count > 0)
        {
            string[] nos = dt.Rows[0][0].ToString().TrimEnd(',').Split(',');
            int[] innerNos = Array.ConvertAll<string, int>(nos, new Converter<string, int>(innerNo => int.Parse(innerNo)));
            if (innerNos[innerNos.Length - 1] == 999)
            {
                for (int i = 0; i < innerNos.Length - 1; i++)
                {
                    if (innerNos[i] + 1 == 999)
                    {
                        txtInnerDept_No.Text = "超过最大值联系管理员";
                        return;
                    }
                    if (innerNos[i] + 1 != innerNos[i + 1])
                    {
                        val = innerNos[i] + 1;
                        break;
                    }
                }
            }
            else
            {
                val = innerNos[innerNos.Length - 1] + 1;
            }
        }
        txtInnerDept_No.Text = val.ToString("000");
    }
}
